<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <style>
       .tag-input{
    position: relative;
    border: 1px solid #cccccc;
    padding: 0 5px;
    display: flex;
    flex-flow: row wrap;
}
.js-input{
    width: 450px;
    height: 22px;
    line-height: 22px;
    font-size: 16px;
    padding: 0;
    margin: 5px 0;
    outline: none;
    border: none;
    width: 6.5em;
    height: 24px;
    line-height: 24px;
}
.tag{
    padding: 0 10px;
    margin: 5px 5px 5px 0;
    background: #25bb9b;
    color: #ffffff;
    height: 24px;
    line-height: 24px;
    border-radius: 12px;
    font-size: 13px;
}
    </style>
</head>

<body>
    <div class="tag-input">
    <span class="tag">前端</span>
    <span class="tag">编程题</span>
    <span class="tag">示例</span>
    <span class="tag">标签</span>
    <input type="text" class="js-input" maxlength="6" placeholder="请输入标签">
</div>
    <script type="text/javascript">
/*
简化版的标签输入框，功能如下：
1. 当用户输入内容并敲回车键时，将输入框的内容在输入框前显示成，并清空输入框内容
2. 当用户敲删除键时，如果输入框当前没有内容，则删除前一个标签
3. 标签需要去掉字符串两端的多余的空格
4. 标签不能为空字符串
5. 标签不能重复，如果输入已存在的内容相同的标签，则不添加，并清空输入框
6. 相关键码值，回车键=13， 删除键=8
 */

var tagInput = {
    isInited: false,
    init: init,
    bindEvent: bindEvent,
    addTag: addTag,
    removeTag: removeTag
};
tagInput.init();

// 初始化
function init() {
    var that = this;
    if (that.isInited) return;
    that.isInited = true;
    // 请修改这一行代码，保存class为js-input的输入框的dom元素引用
    that.input = document.querySelector('.js-input');
    that.bindEvent();
}

// 事件绑定
function bindEvent() {
    var that = this;
    var input = that.input;
    if (!input) return;
    input.addEventListener('keydown', function (event) {
        // 请修改这一行代码，判断用户是否按了回车键
        var isEnter = event.keyCode === 13;
        // 请修改这一行代码，判断用户是否按了删除键
        var isDelete = event.keyCode === 8;

        (isEnter || isDelete) && event.preventDefault();
        isEnter && that.addTag();
        isDelete && that.removeTag();
    });
    input.parentNode.addEventListener('click', function () {
        input.focus();
    });
}

// 添加标签
function addTag() {
    const text = this.input.value.trim()
    if(text === ''){
         this.input.value = ''
         return
    }
    const spans = this.input.parentNode.querySelectorAll('.tag')
    const found =  Array.from(spans).find(ele => ele.textContent === text)
    if(found) {
        this.input.value = ''
        return
    }
    const span = document.createElement('span')
    span.classList.add('tag')
    span.innerHTML = text
    this.input.parentNode.insertBefore(span, this.input)
    this.input.value = ''
}

// 删除标签
function removeTag() {
    const text = this.input.value
    if(text.length === 0 ){
        const spans = this.input.parentNode.querySelectorAll('.tag')
        if(spans.length > 0){
            this.input.parentNode.removeChild(spans[spans.length - 1])
        }
    }
}

    </script>
</body>

</html>